import sys
import time
import pygame
from pygame.locals import *

class timu:


    def __init__(self,path):

        with open(path, encoding="utf-8") as f:
            self.data = f.readlines()
            print(self.data[0])


        pygame.init()
        self.BLACK = (0, 0, 0)
        self.pre_event_key = 0
        self.key_flag = False
        self.seconds = 61
        self.score = 0
        self.typecount = 0
        self.speed = 0
        self.clock_start = 0
        self.time_start = 0
        self.game_over = True
        self.i = 0
        self.index=0
        self.current = 0
        self.input = ''
        self.iptstr = '  '

        self.screen = pygame.display.set_mode((640, 600))
        pygame.display.set_caption('打字游戏')
        self.font1 = pygame.font.Font('SimSun.ttf', 16)
        self.font2 = pygame.font.Font('SimSun.ttf', 60)

        self.database = self.handleWord(self.data[self.index])
        self.word = self.database[0]
        self.text = self.database[1]

        self.draw_background(150, 0, 0)

    def print_text(self,font, x, y, text, color=(0, 0, 0)):
        imgText = font.render(text, True, color)
        self.screen.blit(imgText, (x, y))

    def draw_background(self,r,g,b):
        self.screen.fill((r,g,b))
        self.print_text(self.font1, 0, 0, "请在1分钟内完成:")
        y=30
        for line in self.text:
            self.print_text(self.font1, 0, y, line)
            y+=30

    def handleWord(self,data):
        data = data.replace("\n", '')
        text = data.split("\\n")
        word = ''
        for line in text:
            line = line.replace(",", "")
            line = line.replace(".", "")
            line = line.replace("!", "")
            word = word + line
            word = word + " "
        word = word + "/"
        word = word.split(" ")
        return [word, text]



    def run(self):

        while True:

            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit()
                elif event.type == KEYDOWN:
                    self.key_flag = True
                    if event.key==K_ESCAPE:
                        sys.exit()
                    elif event.type == KEYUP:
                        self.key_flag = False
                    elif event.key == K_RETURN:
                        if self.game_over:
                            self.game_over = False
                            self.clock_start = time.time()
                            self.score = 0
                            self.speed = 0
                            self.typecount = 0
                            clock = self.clock_start
                    elif not self.game_over:
                        current = time.time() - clock
                        if self.seconds < current:
                            self.game_over = True
                            break
                        else:
                            if event.key==K_SPACE:
                                self.i+=1
                                self.input=''
                                self.iptstr+=' '
                            else:
                                if  event.key == K_LSHIFT or event.key == K_RSHIFT:
                                    self.pre_event_key = K_LSHIFT
                                    continue
                                else:
                                    if self.pre_event_key == K_LSHIFT:
                                        self.pre_event_key = None
                                        self.input=self.input+chr(event.key-32)
                                        self.iptstr+=chr(event.key-32)
                                        self.clock_start = time.time()
                                        self.typecount += 1
                                        self.speed = 60 * self.typecount / (self.clock_start - clock)
                                    else:
                                        self.input=self.input+chr(event.key)
                                        self.iptstr +=chr(event.key)
                                        self.clock_start = time.time()
                                        self.typecount += 1
                                        self.speed = 60 * self.typecount /(self.clock_start - clock)
                                if self.input ==self.word[self.i]:
                                    self.score+=1
                                if event.key==K_TAB:
                                    self.index += 1
                                    if self.index < len(self.data):
                                        self.database = self.handleWord(self.data[self.index])
                                        self.word = self.database[0]
                                        self.text = self.database[1]
                                        self.iptstr='  '
                                        self.i=0
                                        continue
            if self.key_flag:
                self.print_text(self.font1, 500, 0, "<key>")

            if not self.game_over:
                current = time.time() - clock
                if self.seconds < current:
                    self.game_over = True

                if self.speed <= 30:
                   self.draw_background(255, 0, 0)
                else:
                    if self.speed <= 35:
                        self.draw_background(200, 50, 0)
                    else:
                        if self.speed <= 40:
                            self.draw_background(140, 80, 0)
                        else:
                            if self.speed <= 45:
                                self.draw_background(120, 130, 0)
                            else:
                                if self.speed <= 50:
                                    self.draw_background(60, 200, 0)
                                else:
                                    if self.speed <= 55:
                                        self.draw_background(40, 220, 0)
                                    else:
                                        if self.speed <= 60:
                                            self.draw_background(20, 240, 0)
                                        else:
                                            self.draw_background(0, 255, 0)




            if self.game_over:
                self.print_text(self.font1, 0, 100, "按enter键开始 按空格键继续下个字母 ")
                self.print_text(self.font1, 0, 130, "如果在1分钟内，按tab键可以开始下一行 ")
            if not self.game_over:
                self.print_text(self.font1, 0, 150, "输入正确字母个数: %s : " % self.score)
                self.print_text(self.font1, 0, 170, "时间: " + str(int(self.seconds-current)))
                self.print_text(self.font1, 0, 200, "速度是 : " + str(int(self.speed)) + " 字符/分钟")
                self.print_text(self.font1, 0, 320, '在这里输入:', self.BLACK)
                self.print_text(self.font1, 0, 340, self.iptstr, self.BLACK)
                try:
                    self.print_text(self.font2, 0, 250, self.word[self.i], self.BLACK)
                except:

                    self.index += 1
                    if self.index < len(self.data):

                        self.database = self.handleWord(self.data[self.index])
                        self.word = self.database[0]
                        self.text = self.database[1]
                        self.iptstr = '  '
                        self.i = 0
                        continue
                    else:
                        self.print_text(self.font1, 0, 380, '练习文本已经输入完成', self.BLACK)

            pygame.display.update()

if __name__ == "__main__":
    timu = timu('text.txt')
    timu.run()